package com.mrd.gtimp.business.service;

import com.mrd.base.BaseBiz;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.business.entity.BaseBusiness;
import com.mrd.gtimp.business.entity.Declaration;
import com.mrd.spring.repository.BaseRepository;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

@Service
public class BusinessBiz extends BaseBiz<BaseBusiness> {

    @Resource
    private DeclarationBiz declarationBiz;

    public void saveBusinesses(List<? extends BaseBusiness> baseBusinesses) throws Exception {
        saveBusinesses(baseBusinesses, new ArrayList<List<String>>());
    }

    /*
     * (non-Javadoc)
     * @see com.mrd.gtimp.business.biz.BusinessBiz#saveBusinesses(java.util.List, java.util.List)
     */
    @SuppressWarnings({"unchecked", "rawtypes"})

    public void saveBusinesses(List<? extends BaseBusiness> baseBusinesses,
                               List<List<String>> properties) throws Exception {
        WebApplicationContext wc = WebApplicationContextUtils
                .getWebApplicationContext(HttpUtils.getServletContext());
        int i = 0;
        for (BaseBusiness baseBusiness : baseBusinesses) {
            // 获取注入的业务处理对象名如bookingBiz,spring中的名称第一个字母小写
            StringBuffer biz = new StringBuffer();
            String className = baseBusiness.getClass().getSimpleName();
            biz.append(Character.toLowerCase(className.charAt(0)));// 将起始字符换成小写
            biz.append(className.substring(1));// 添加其他内容
            biz.append("Biz");
            if (baseBusiness instanceof Declaration) {
                if (properties == null || properties.size() == 0) {
                    declarationBiz.saveBusiness((Declaration) baseBusiness, null);
                } else {
                    declarationBiz.saveBusiness((Declaration) baseBusiness, properties.get(i));
                }
            }
            i++;
        }
    }


    @Resource
    @Qualifier("businessDao")
    public void setBaseRepository(BaseRepository<BaseBusiness, String> baseRepository) {
        super.baseRepository = baseRepository;
    }


}
